package mymac.com.test_3_1;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by mymac on 2017/2/26.
 */

public class DataFragment extends Fragment{
    private SharedPreferences preferences;
    private ListView listView;
    private MyAdapter adapter;
    private ArrayList<DataItem> datas = new ArrayList<>();
    private String token;
    private Button btn_userAdd;
    private AlertDialog builder;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_data,null);
        listView = (ListView) view.findViewById(R.id.lv_data);
        btn_userAdd = (Button) view.findViewById(R.id.btn_userAdd);
        preferences = getActivity().getSharedPreferences("token", Activity.MODE_PRIVATE);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        token = preferences.getString("token","");
        this.registerForContextMenu(listView);
        setOnClick();
    }

    @Override
    public void onResume() {
        super.onResume();
        loadData();
        datas.clear();
    }

    private void setOnClick() {
        btn_userAdd.setOnClickListener(new MyOnClickListenerUser());
    }

    class MyOnClickListenerUser implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getActivity(), AddUserActivity.class);
            startActivity(intent);
        }
    }

    public void loadData(){
        final String address = "http://a.xl18z.cn/api/users/list?token=" + token;
        HttpActivity.getInstance().getJson(address, new DataCallBack() {
                    @Override
                    public void onErr(Object object) {
                        JSONObject json = (JSONObject) object;
                        try {
                            JSONObject record = json.getJSONObject("record");
                            JSONArray dataArr = record.getJSONArray("data");

                            for (int i=0; i<dataArr.length(); i++){
                                JSONObject temp = (JSONObject) dataArr.get(i);
                                String id = temp.getString("id");
                                String name = temp.getString("name");
                                String department;
                                if (temp.length() <= 2){
                                    department = "无部门";
                                } else {
                                    department = temp.getString("department");
                                }
                                DataItem data = new DataItem();
                                data.id = id;
                                data.name = name;
                                data.department = department;

                                datas.add(data);
                                adapter = new MyAdapter();
                                listView.setAdapter(adapter);
                                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                    @Override
                                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                        view.showContextMenu();
                                        contentMenus();
                                    }
                                });
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void contentMenus() {
        listView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
                contextMenu.add(0, 0, 0, "修改");
            }
        });
    }
    // 菜单响应函数
    public boolean onContextItemSelected(MenuItem item) {
        final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        switch (item.getItemId()) {
            // 修改操作
            case 0:
                modification(info);
                break;
        }
        return super.onContextItemSelected(item);
    }
    //修改item
    private void modification(AdapterView.AdapterContextMenuInfo info) {
        //final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
         final String id = ((TextView) info.targetView.findViewById(R.id.tv_data_id)).getText().toString();
         final String name = ((TextView) info.targetView.findViewById(R.id.tv_data_name)).getText().toString();
         String department = ((TextView) info.targetView.findViewById(R.id.tv_data_department)).getText().toString();

        ShowView.getInstance().showView(getActivity(), R.layout.activity_updatauser, new ShowCallBack() {
            @Override
            public void showBuiler(final Object obj1, Object obj2) {
                Window window = (Window) obj1;
                builder = (AlertDialog) obj2;
                final EditText et_updataName = (EditText) window.findViewById(R.id.et_updataName);
                final EditText et_updataPsw = (EditText) window.findViewById(R.id.et_updataPsw);
                final EditText et_updataDeps = (EditText) window.findViewById(R.id.et_updataDeps);
                et_updataName.setHint(name);
                Button btn_mod = (Button) window.findViewById(R.id.btn_updata);

                btn_mod.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String name = et_updataName.getText().toString().trim();
                        String psw = et_updataPsw.getText().toString().trim();
                        String deps = et_updataDeps.getText().toString().trim();
                        String address = "http://a.xl18z.cn/api/users/update?token=" + token  + "&name=" + name + "&password=" + psw + "&department=" + deps + "&id=" + id;
                        HttpActivity.getInstance().getErrMsg(address, new DataCallBack() {
                            @Override
                            public void onErr(Object object) {
                                String errmsg = (String) object;
                                if ("ok!".equals(errmsg)) {
                                    datas.clear();
                                    loadData();
                                    builderCancel(builder,errmsg);
                                } else {
                                    builderCancel(builder,errmsg);
                                }
                            }
                        });
                    }
                });
            }
        });
    }
    public void builderCancel(AlertDialog builder, String errmsg) {
        builder.cancel();
        Toast.makeText(getActivity(), "" + errmsg, Toast.LENGTH_SHORT).show();
    }

    class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return datas.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            View contentView;
            if (view == null){
                contentView = View.inflate(getActivity().getApplicationContext(),R.layout.activity_data_item,null);
            } else {
                contentView = view;
            }
            TextView id = (TextView) contentView.findViewById(R.id.tv_data_id);
            TextView name = (TextView) contentView.findViewById(R.id.tv_data_name);
            TextView department = (TextView) contentView.findViewById(R.id.tv_data_department);
            id.setText(datas.get(i).getId());
            name.setText(datas.get(i).getName());
            department.setText(datas.get(i).getDepartment());
            return contentView;
        }
    }
}
